﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Harkon.AppServer.cOne.Service;
using Harkon.AppServer.cOne.Registry;
using Spring.Context;
using System.Diagnostics;

namespace Harkon.AppServer.cOne.Service
{
    public class ServiceLifecycleManager : AbstractService, IServiceLifecycleManager, IApplicationContextAware
    {
        public ComponentInformation ComponentInformation { get; set; }

        public void ChannelClosed(object sender, EventArgs e)
        {
            FireChannelClosed();
        }

        void FireChannelClosed()
        {
            Stop();
        }

        #region ILifecycleAware Members

        public override bool Init()
        {
            if (base.Init())
            {
                foreach (var serviceName in ApplicationContext.GetObjectNamesForType(typeof(ILifecycleAware)))
                {
                    dynamic service = ApplicationContext[serviceName];
                    if (
                        service.GetType() != typeof(ServiceLifecycleManager)
                        && !service.GetType().FullName.Contains("Castle.Proxies.")
                        )
                        service.Init();
                }
                return true;
            }
            return false;
        }

        public override bool Start()
        {
            if (base.Start())
            {
                foreach (var serviceName in ApplicationContext.GetObjectNamesForType(typeof(ILifecycleAware)))
                {
                    dynamic service = ApplicationContext[serviceName];
                    if (
                        service.GetType() != typeof(ServiceLifecycleManager)
                        && !service.GetType().FullName.Contains("Castle.Proxies.")
                        )
                        service.Start();
                }
                return true;
            }
            return false;
        }

        public override bool Stop()
        {
            if (base.Stop())
            {
                foreach (var serviceName in ApplicationContext.GetObjectNamesForType(typeof(ILifecycleAware)))
                {
                    dynamic service = ApplicationContext[serviceName];
                    if (
                        service.GetType() != typeof(ServiceLifecycleManager)
                        && !service.GetType().FullName.Contains("Castle.Proxies.")
                        )
                        service.Stop();
                }
                return true;
            }
            return false;
        }

        #endregion

        #region IApplicationContextAware Members

        public IApplicationContext ApplicationContext { get; set; }

        #endregion
    }
}
